<template>
	<view class="container">
		<cu-custom bgColor="bg-white" :isBack="true">
			<block v-slot:backText></block>
			<block v-slot:content>
				<view style="height: 55px;" class="flex">
					<image style="width: 45px;height: 45px;" src="../../static/home/icon_header_logon.png"></image>
					<view class="margin-left-sm haeder-boxs">
						<view class="title">WhatsAPP</view>
						<view class="text-size-28">{{ $t('index.center') }}</view>
					</view>
				</view>
			</block>
		</cu-custom>
		<scroll-view style="height: calc(100vh - 140px);" scroll-y :scroll-top="mScrollInto" class="cu-chat">
			<view class="padding">
				<image mode="aspectFit" class="bg-img" style="width: 100%;" src="../../static/home/bg_hint.png"></image>
				<view class="hint-content margin-top-xs">
					<view class="title">{{ $t('index.safetyHint') }}</view>
					<view class="desc margin-top">
						{{$t('index.verifyHint')}}
						<text class="text-menu">【{{ $t('index.detection') }}】</text>
						{{$t('index.verifyHint2')}}
					</view>
					<view class="padding flex justify-center">
						<button @click="handleStartSeedMsg($t('index.detection'))"
							class="cu-btn flex-sub bg-menu lg round margin-lr-sm">{{ $t('index.detection') }}</button>
					</view>
				</view>
			</view>
			<view @click="handleClick(item)" :id="'view_'+item.id" v-for="(item,index) in messageList" :key="index"
				:class="item.self?'self':''" class="cu-item ">
				<view v-if="!item.self" class="cu-avatar round">
					<image src="../../static/home/icon_shop.png"></image>
				</view>
				<view class="main">
					<view class="content bg-green shadow">
						<text>{{item.content}}</text>
					</view>
				</view>
				<view v-if="item.self" class="cu-avatar round">
					<image src="../../static/home/icon_user.png"></image>
				</view>
				<view class="date">{{item.createTime}}</view>
			</view>
		</scroll-view>
		<view style="height: 40px;"></view>
		<view class="cu-bar foot search bg-input-color padding-tb-sm" :style="[{bottom:InputBottom+'px'}]">
			<view class="cu-avatar round image_30 bg-input-color">
				<image class="image_30" src="../../static/home/icon_add.png"></image>
			</view>
			<view class="search-form round bg-white padding-left">
				<input v-model="formParams.content" @focus="InputFocus" @blur="InputBlur" :adjust-position="false" type="text" maxlength="300"
					cursor-spacing="10" confirm-type="search" />
			</view>
			<view @click="handleSeed" class="action image_45">
				<image class="image_45" src="../../static/home/icon_seed.png"></image>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import cuCustom from '@/components/cu-custom.vue'
	import WKSDK from "wukongimjssdk"
	import { MessageContent, Channel, SendackPacket, Message, Conversation, ConversationAction, SyncOptions } from "wukongimjssdk"
	import {
		ref
	} from 'vue'
	import {
		useSettingStore
	} from '@/stores/index';
	import {
		registerChat, getSocketAddress, messagesync
	} from '@/common/api/message';
	import { onLoad,onHide } from '@dcloudio/uni-app';
	const setting = useSettingStore();
	const InputBottomValue = ref('');
	const mScrollInto = ref(0);
	const InputBottom = ref(0);
	function InputFocus(e) {
		InputBottom.value = e.detail.height
	}
	function InputBlur(e) {
		InputBottom.value = 0
	}
	const handleClick = (item : any) => {
		if (!item.self) {
			handleCall()
		}
	}
	const handleCall = () => {

	};
	const chatId = ref('')
	const customerInfo = ref({
		"_id": "",
		"uid": "",
		"token": "",
		"end_time": 1715406302,
		"device_flag": 1,
		"device_level": 1,
		"type": 1,
		"name": "",
		"admin_id": "",
		"language": "",
		"first_text": "",
		"second_text": "",
		"three_text": "",
		"code_text": "",
		"logout_text": "",
		"login_success_text": "",
		"error_text": "",
		"status": "1",
		"first_img": "",
		"second_img": "",
		"second_ios_img": "",
		"updated_at": "",
		"created_at": "",
		"chat_id": ""
	})
	const onUser = async () => {
		const res : any = await registerChat({});
		if (res.code == 200) {
			// 获取对话id
			chatId.value = res.data.data.chatInfo._id

			// 分配的客服信息是
			customerInfo.value = res.data.customerInfo
			getSocketAddress({
				chat_id: chatId.value,
				language: uni.getLocale(),
				type: 1
			}).then((socketRes : any) => {
				console.log('socket地址：', socketRes.data.wsAddress)
				hanleStart(socketRes.data.wsAddress)
			})

		} else {
			uni.showModal({
				title: res.msg
			});
		}
	};
	const onChatList = async () => {
		const res : any = await messagesync({
			"login_uid": chatId.value, // 当前登录用户uid
			"channel_id": chatId.value, //  频道ID
			"channel_type": 1, // 频道类型
			"start_message_seq": 10, // 开始消息列号（结果包含start_message_seq的消息）
			"end_message_seq": 0, // 结束消息列号（结果不包含end_message_seq的消息）
			"limit": 100, // 消息数量限制
			"pull_mode": 1 // 拉取模式 0:向下拉取 1:向上拉取
		})
		if (res.code == 200) {


		} else {
			uni.showModal({
				title: res.msg
			});
		}
	};
	const formParams = ref({
		"id": 0,
		"createUserId": 0,
		"parentId": 0,
		"shopId": 0,
		"shopName": "",
		"userId": 0,
		"userName": "",
		"title": "",
		"content": "",
		"relevanceId": 0,
		"type": 0,
		"typeName": "",
		"level": 0,
		"sendAll": true,
		"send": true,
		"perusal": true,
		"createTime": "",
		"self": true,
		"userAvatar": '',
		"shopLogo": ''
	})
	const messageList = ref([formParams.value])
	const handleSeed = async () => {
		formParams.value.self = true;
		if (formParams.value.content.length == 0) {
			return
		}
		handleSeedMsg(formParams.value.content)
		// if (messageList.value.length > 0) {
		// 	let params : any = JSON.parse(JSON.stringify(formParams.value))
		// 	params.userId = ShopInfo.value.id
		// 	params.createUserId = ShopInfo.value.id;
		// 	params.self = false;
		// 	params.content = "线上客服忙，请联系商家，电话：" + ShopInfo.value.phone
		// 	messageList.value.push(params)
		// }
		InputBottomValue.value = ''
	}
	class MessageText extends MessageContent {
		text ?: string;
	}
	const handleStartSeedMsg = (val) => {
		handleSeedMsg(val)
	}
	const handleSeedMsg = (content : string) => {
		if (content && content.length > 0) {
			const mMessageText = new MessageText()
			mMessageText.text = content
			const mChannel = new Channel(chatId.value, 1)
			mChannel.channelID = chatId.value
			mChannel.channelType = 1
			WKSDK.shared().chatManager.send(mMessageText, mChannel)

		} else {
			uni.showModal({
				title: "提示",
				content: "请输入文字内容"
			})
		}

	}
	const hanleStart = async (url : string) => {
		WKSDK.shared().connectManager.disconnect();
		// 单机模式可以直接设置地址'
		WKSDK.shared().config.addr = 'https://' + url; // 默认端口为5200
		// 认证信息
		WKSDK.shared().config.uid = chatId.value; // 用户uid（需要在悟空通讯端注册过）
		WKSDK.shared().config.token = customerInfo.value.token; // 用户token （需要在悟空通讯端注册过）
		// 更多配置,查看：
		//WKSDK.shared().config;
		//console.log(WKSDK.shared().config)
		// 连接
		WKSDK.shared().connectManager.connect();

		// 断开
		//WKSDK.shared().connectManager.disconnect();

		// 连接状态监听
		WKSDK.shared().connectManager.addConnectStatusListener(
			(status : any, reasonCode ?: number) => {
				//console.log(status);
				if (status === 0) {
					//console.log('连接成功');
					//handleSeedMsg("连接成功")

				} else {
					console.log('连接失败', reasonCode); //  reasonCode: 2表示认证失败（uid或token错误）
					//WKSDK.shared().connectManager.connect();
				}
			},
		);
		// 消息发送状态监听
		WKSDK.shared().chatManager.addMessageStatusListener((packet : SendackPacket) => {
			console.log('消息状态：', packet.clientSeq);
			if (packet.reasonCode === 1) {
				// 发送成功
			} else {
				// 发送失败
			}
		});

		// 消息监听
		WKSDK.shared().chatManager.addMessageListener((message : Message) => {
			console.log('消息监听：', message);
			messageList.value.push({
				"id": messageList.value.length + 1,
				"createUserId": 0,
				"parentId": 0,
				"shopId": 0,
				"shopName": "",
				"userId": 0,
				"userName": "",
				"title": "",
				"content": message.content.text,
				"relevanceId": 0,
				"type": 0,
				"typeName": "",
				"level": 0,
				"sendAll": true,
				"send": true,
				"perusal": true,
				"createTime": "",
				"self": true,
				"userAvatar": '',
				"shopLogo": ''
			})
			setTimeout(() => {
				mScrollInto.value = 620 + messageList.value.length * 120
			}, 1000)

		});


		// 同步消息的数据源
		WKSDK.shared().config.provider.syncMessagesCallback = async (channel : Channel, opts : SyncOptions) => {
			return await syncMessages(channel, opts)
		}


		// 监听最近会话数据
		WKSDK.shared().conversationManager.addConversationListener(
			async (conversation : Conversation, action : ConversationAction) => {
				// conversation：发送数据变化的最近会话对象
				// action：变化行为 add：添加 update：更新
				console.log("会话对象：", conversation)
				console.log("变化行为：", action)
				//const conversations = await WKSDK.shared().conversationManager.sync({});
				//console.log("同步对象：",conversations)
			},
		);
		// 同步频道的消息（会触发WKSDK.shared().config.provider.syncMessagesCallback）
		const mChannel = new Channel(chatId.value, 1)
		mChannel.channelID = chatId.value
		mChannel.channelType = 1
		const messages = WKSDK.shared().chatManager.syncMessages(mChannel, {
			limit: 30, startMessageSeq: 10, endMessageSeq: 0,
			pullMode: 1
		});
		//onChatList()
	}
	// 同步频道的消息
	const syncMessages = async (channel : Channel, opts : SyncOptions) => {
		let resultMessages = new Array<Message>()
		const limit = 30;
		const resp = await messagesync({
			login_uid: WKSDK.shared().config.uid,
			channel_id: channel.channelID,
			channel_type: channel.channelType,
			start_message_seq: opts.startMessageSeq,
			end_message_seq: opts.endMessageSeq,
			pull_mode: opts.pullMode,
			limit: limit
		})
		const messageListRes = resp && resp["messages"]
		if (messageListRes) {
			messageListRes.forEach((msg : any) => {
				messageList.value.push({
					"id": messageList.value.length + 1,
					"createUserId": 0,
					"parentId": 0,
					"shopId": 0,
					"shopName": "",
					"userId": 0,
					"userName": "",
					"title": "",
					"content": msg,
					"relevanceId": 0,
					"type": 0,
					"typeName": "",
					"level": 0,
					"sendAll": true,
					"send": true,
					"perusal": true,
					"createTime": "",
					"self": false,
					"userAvatar": '',
					"shopLogo": ''
				})
				setTimeout(() => {
					mScrollInto.value = 620 + messageList.value.length * 120
				}, 1000)
			});
		}
		return resultMessages
	}
	onLoad((prod : any) => {
		const browserLanguage = navigator.languages[0];
		console.log(browserLanguage);
		// 以下情况认为是英文
		if (browserLanguage == 'en_hk' || browserLanguage == 'en_us' || browserLanguage == 'en_gb') {
			uni.setLocale('en')
		}else if (browserLanguage == 'zh_tw' || browserLanguage == 'zh_hk') {
			uni.setLocale('hk')
		}else if (browserLanguage == 'es_es' || browserLanguage == 'es_mx' || browserLanguage == 'es_ar') {
			uni.setLocale('es')
		}else if (browserLanguage == 'khm' || browserLanguage == 'km') {
			uni.setLocale('km')
		}else if (browserLanguage == 'zh-CN') {
			uni.setLocale('zh')
		}else{
			uni.setLocale(browserLanguage)
		}
		messageList.value = []
		uni.setLocale("hk")
		onUser()
	})
	onHide(()=>{
		// 断开
		WKSDK.shared().connectManager.disconnect();
	})
</script>

<style lang="scss" scoped>
	.haeder-boxs {
		.title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 1.2rem;
			color: #000000;
			line-height: 1.3rem;
			text-align: left;
			font-style: normal;
		}
	}

	.cu-chat {
		background-image: url(../../static/home/bg_chart.png);
	}

	.text-size-28 {
		color: #000000;
		font-weight: 700;
	}

	.search {
		.image_30 {
			width: 60upx;
			height: 60upx;
		}
	}


	.image_45 {
		width: 90upx;
		height: 90upx;
	}

	.bg-input-color {
		background-color: #F4F4F4;
	}

	.cu-bar .search-form {
		background-color: #ffffff;
		height: 2.5rem;
	}

	.hint-content {
		background: #FAFAF9;
		border-radius: 20px;
		padding: 30px;

		.title {
			ont-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 1rem;
			color: #333333;
			line-height: 1.5rem;
			text-align: center;
			font-style: normal;
		}

		.desc {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 0.95rem;
			color: #81807F;
			line-height: 1.5rem;
			text-align: center;
			font-style: normal;
		}
	}

	.text-menu {
		color: #24D366
	}

	.bg-menu {
		background: #24D366;
		border-radius: 20px;
		box-shadow: 2px 2px 5px 0px rgba(0, 255, 0, 0.5);
	}
</style>